<template>
  <div>
    <el-popover ref="iconListPopover" :virtual-ref="iconInputRef"
                  placement="bottom-start" trigger="click" virtual-triggering
                  :visible="visible" width="458px" popper-class="mod-menu__icon-popover">
      <div class="mod-menu__icon-inner">
        <el-scrollbar>
          <div class="mod-menu__icon-list">
            <el-button v-for="(item, index) in iconList" :key="index" @click="iconActiveHandle(item)" :class="{ 'is-active': item === modelValue }">
              <icon-svg :name="item"></icon-svg>
            </el-button>
          </div>
        </el-scrollbar>
      </div>
    </el-popover>
    <el-input ref="iconInputRef" v-model="modelValue" :readonly="true" @focus="visible = true" @blur="visible = false" placeholder="请选择图标" class="icon-list__input"></el-input>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";

// 属性定义
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
  },
});

// 是否显示
const visible = ref(false);

// 所有图标列表
const iconList = ref([]);

// 图标输入框引用
const iconInputRef = ref();

// 父级组件的自定义事件
const emit = defineEmits(['update:modelValue']);

// 组件挂载完成后执行
onMounted(() => {
  // 获取所有的 iconfont 图标
  const nodeArray = Array.from(document.querySelectorAll('symbol'));
  const names = nodeArray.map(item => item.id.indexOf('icon-') != -1 ? item.id.substring(5) : item.id);
  iconList.value = names;
});

// 图标选中
const iconActiveHandle = (iconName) => {
  emit("update:modelValue", iconName);
  visible.value = false;
};
</script>

<style lang="scss">
.mod-menu {

  .menu-list__input,
  .icon-list__input {
    > .el-input__inner {
      cursor: pointer;
    }
  }

  &__icon-popover {
    width: 458px !important;
    overflow: hidden;
  }

  &__icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &__icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
  
  .icon-list__tips {
    font-size: 18px;
    text-align: center;
    color: #e6a23c;
    cursor: pointer;
  }
}
</style>
